<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
    <!-- 课程名称 -->
    <el-form-item label="课程名称" prop="courseName">
      <el-input v-model="formData.courseName" placeholder="请输入课程名称" />
    </el-form-item>

    <!-- 开课时间 -->
    <el-form-item label="开课时间" prop="startTime">
      <el-date-picker
        v-model="formData.startTime"
        type="datetime"
        value-format="YYYY-MM-DD HH:mm:ss"
        placeholder="请选择开课时间"
        style="width: 100%"
      />
    </el-form-item>

    <!-- 最大选课人数 -->
    <el-form-item label="最大选课人数" prop="maxStudents">
      <el-input-number
        v-model="formData.maxStudents"
        :min="1"
        placeholder="请输入最大人数"
      />
    </el-form-item>

    <!-- 是否公开 -->
    <el-form-item label="是否公开" prop="isPublic">
      <el-switch
        v-model="formData.isPublic"
        active-value="true"
        inactive-value="false"
      />
    </el-form-item>

    <!-- 课程说明 -->
    <el-form-item
      label="课程说明"
      prop="description"
      style="align-items: flex-start"
    >
      <el-input
        v-model="formData.description"
        placeholder="课程说明"
        type="textarea"
      />
    </el-form-item>

    <!-- 提交按钮 -->
    <el-form-item>
      <el-button type="primary" @click="handleSubmit">保存</el-button>
      <el-button @click="$emit('cancel')">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { courseApi } from "../../api/courseApi";

const emit = defineEmits(["success", "cancel"]);
const formRef = ref(null);
const formData = reactive({
  courseName: "",
  startTime: "",
  maxStudents: 1000,
  isPublic: "false",
  description: "",
});
const rules = {
  courseName: [
    { required: true, message: "请输入课程名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
  ],
  status: [{ required: true, message: "请选择课程状态", trigger: "change" }],
  // isPublic: [{ required: true, message: "请选择是否公开", trigger: "change" }],
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await courseApi.addCourse(formData);
        if (res.code === 1) {
          ElMessage.success("新增课程成功");
          emit("success");
        }
      } catch (error) {
        console.error("新增课程失败:", error);
      }
    }
  });
};
</script>
